import { AsyncStorage } from 'react-native';
import Request from "../utils/Request";
import constant from "../utils/constant";
import { kAuthorization } from "../constant";
import RouterServer from "../utils/RouterServer";
const { Toast } = require('antd-mobile');
const STORAGE_KEY = "STORAGE_KEY_active";
const model = {
    namespace: 'active',
    state: {
        loading: false,
        list: null,
        typeList: null,
        userJoinedActiveList: [],
        selectedActiveTypes: [],
        activeDetail: null,
    },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *saveToStorage({ payload }, { call }) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        *restoreFromStorage({ payload }, { call, put, select }) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: Object.assign({}, JSON.parse(data))
            });
        },
        *fetchList({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            yield put({ type: 'save', payload: { loading: true } });
            payload['userId'] = auth.userInfo.id;
            payload['Authorization'] = auth.token_type + ' ' + auth.access_token;
            payload['ids'] = payload['ids'];
            const result = yield call(Request.get, Request.getApi().filterActiveList, payload);
            yield put({ type: 'save', payload: { loading: false } });
            if (result) {
                yield put({ type: 'save', payload: { list: result } });
            }
        },
        *joinOrLeaveActive({ payload }, { put, select, call }) {
            const auth = yield select(state => state.auth);
            const active = yield select(state => state.active);
            if (!payload.from) {
                const act = payload.active;
                const param = {
                    Authorization: auth.token_type + ' ' + auth.access_token,
                    params: { userId: auth.userInfo.id, activityId: act.activity.id }
                };
                param['Content-Type'] = `application/json`;
                let index = active.list.content.indexOf(act);
                const isJoin = act['isJoin'] === '0' ? '1' : '0';
                const res = yield call(Request.post, Request.getApi().joinActive + `/${isJoin}`, param);
                if (res) {
                    act.isJoin = isJoin;
                    active.list.content[index] = act;
                    yield put({ type: 'save', payload: Object.assign({}, active) });
                    let tip = isJoin === '1' ? '您已经加入该活动!' : '您已经离开该活动';
                    Toast.success(tip, constant.ToastDuration);
                }
                yield put({ type: 'fetchUserActiveList' });
            }
            else if (payload.from === 'myActives') {
                const act = payload.active;
                const param = {
                    Authorization: auth.token_type + ' ' + auth.access_token,
                    params: { userId: auth.userInfo.id, activityId: act.id }
                };
                param['Content-Type'] = `application/json`;
                let index = active.userJoinedActiveList.indexOf(act);
                const isJoin = act['isJoin'] === '0' ? '1' : '0';
                const res = yield call(Request.post, Request.getApi().joinActive + `/${isJoin}`, param);
                if (res) {
                    act.isJoin = isJoin;
                    active.userJoinedActiveList[index] = act;
                    active.activeDetail = act;
                    yield put({ type: 'save', payload: Object.assign({}, active) });
                    let tip = isJoin === '1' ? '您已经加入该活动!' : '您已经离开该活动';
                    Toast.success(tip, constant.ToastDuration);
                }
                yield put({ type: 'fetchUserActiveList' });
            }
        },
        *fetchTypeList({ payload }, { put, call, select }) {
            const auth = yield select(state => state.auth);
            let active = yield select(state => state.active);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const result = yield call(Request.get, Request.getApi().activeTypeList, payload);
            if (result) {
                if (payload.loadmore) {
                    let content = active.typeList.content;
                    active.typeList = result;
                    active.typeList.content = content.concat(result.content);
                }
                else {
                    active.typeList = result;
                }
                yield put({ type: 'save', payload: Object.assign({}, active) });
            }
        },
        *fetchUserActiveList({ payload }, { put, call, select }) {
            yield put({ type: 'save', payload: { userJoinedActiveList: [] } });
            const auth = yield select(state => state.auth);
            let p = {};
            p[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const userJoinedActiveList = yield call(Request.get, Request.getApi().userJoinedActiveList + `/${auth.userInfo.id}`, p);
            if (userJoinedActiveList && Array.isArray(userJoinedActiveList)) {
                yield put({
                    type: 'save',
                    payload: { userJoinedActiveList }
                });
            }
        },
        *applyActiveFilter({ payload }, { put, call, select }) {
            yield put({
                type: 'save',
                payload: { selectedActiveTypes: payload.selectedActiveTypes }
            });
            const active = yield select(state => state.active);
            if (active.selectedActiveTypes.length > 0) {
                yield put({
                    type: 'fetchList',
                    payload: {
                        pi: 1,
                        ps: 10,
                        ids: active.selectedActiveTypes.join(',')
                    }
                });
            }
            else {
                yield put({ type: 'clear' });
            }
            yield put({ type: 'fetchUserActiveList' });
            yield call(RouterServer.pop);
        },
        *goToDetail({ payload }, { put, call }) {
            yield put({
                type: 'save',
                payload
            });
            yield call(RouterServer.push, 'activeDetail');
        },
        *clear({ payload }, { put }) {
            yield put({
                type: 'save', payload: {
                    activeList: null,
                }
            });
        }
    },
    subscriptions: {
        setup({ dispatch }) {
        }
    },
};
export default model;
